package cn.jiedh.app.meiweidk.app;

import android.app.Activity;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.support.multidex.MultiDexApplication;
import android.text.TextUtils;
import android.util.Config;

import com.tencent.bugly.crashreport.CrashReport;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;

import cn.jiedh.app.meiweidk.Utils.KeyConstans;
import cn.jiedh.app.meiweidk.Utils.tool.L;
import cn.jiedh.app.meiweidk.Utils.tool.OverallData;
import cn.jiedh.app.meiweidk.Utils.tool.SPUtils;
import cn.jiedh.app.meiweidk.Utils.tool.T;

import org.xutils.DbManager;
import org.xutils.x;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Stack;

import cn.jpush.android.api.JPushInterface;

/**
 * @name：
 * @author： 周毅
 * @phone： 15826080712
 * @createTime： 2017/7/31
 * @modifyTime： 2017/7/31
 * @explain：
 */

public class MyApp extends MultiDexApplication {


    private static Stack<Activity> activityStack;

    String TAG = "HouHanflowApplication";
    public static Context mContext;
    private static MyApp getinstance;
    private DbManager.DaoConfig daoConfig;

    public synchronized static MyApp getInstance() {
        if (null == getinstance) {
            getinstance = new MyApp();
        }
        return getinstance;
    }

    public DbManager.DaoConfig getDaoConfig() {
        return daoConfig;
    }

    @Override
    public void onCreate() {
        super.onCreate();//log开关
        this.mContext = getApplicationContext();
        L.isDebug=true;
        T.init(getApplicationContext());
        UMConfigure.setLogEnabled(true);
        UMConfigure.init(this,UMConfigure.DEVICE_TYPE_PHONE,null);
        //设置环境
        EnvConfig.initEnv(EnvConfig.EnvType.ENV_RELEASE);
//        EnvConfig.initEnv(EnvConfig.EnvType.ENV_TEST);
        getinstance = (MyApp) getApplicationContext();


        daoConfig = new DbManager.DaoConfig()
                .setDbName("mxk.db")//创建数据库的名称 // TODO: 2017/11/6 0006
                .setDbVersion(1)//数据库版本号
                .setDbUpgradeListener(new DbManager.DbUpgradeListener() {
                    @Override
                    public void onUpgrade(DbManager db, int oldVersion, int newVersion) {

                    }
                });//数据库更新操作
        x.Ext.init(this);//Xutils初始化
        SPUtils.initSPUtil(getApplicationContext());

        JPushInterface.setDebugMode(true);    // 设置开启日志,发布时请关闭日志
        JPushInterface.init(this);            // 初始化 JPush
        /**
         * 记录崩溃日志并处理崩溃的异常
         */
        initBugfy();
        /**
         * 获取渠道名
         * @param context 此处习惯性的设置为activity，实际上context就可以
         * @return 如果没有获取成功，那么返回值为空
         */
        String channelName = "HW";
        try {
            PackageManager packageManager = this.getPackageManager();
            if (packageManager != null) {
                //注意此处为ApplicationInfo 而不是 ActivityInfo,因为友盟设置的meta-data是在application标签中，而不是某activity标签中，所以用ApplicationInfo
                ApplicationInfo applicationInfo = packageManager.
                        getApplicationInfo(this.getPackageName(), PackageManager.GET_META_DATA);
                if (applicationInfo != null) {
                    if (applicationInfo.metaData != null) {
                        channelName = String.valueOf(applicationInfo.metaData.get("BaiduMobAd_CHANNEL"));
                    }
                }

            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        OverallData.setChannel(channelName);
        //各个平台的配置，建议放在全局Application或者程序入口
        initPush();
    }

    /**
     * 初始化分享
     */
    private void initPush() {
        //友盟



        MobclickAgent.setScenarioType(this, MobclickAgent.EScenarioType.E_UM_NORMAL);//友盟统计 场景设置
        MobclickAgent.openActivityDurationTrack(false);//禁止默认的页面统计方式，这样将不会再自动统计Activity。
        MobclickAgent.setSessionContinueMillis(30 * 1000);//来自定义这个间隔（参数单位为毫秒）。
        MobclickAgent.enableEncrypt(true);//SDK会对日志进行加密。加密模式可以有效防止网络攻击，提高数据安全性。
        MobclickAgent.setCatchUncaughtExceptions(true);//友盟true捕获异常崩溃信息
        MobclickAgent.setDebugMode(L.isDebug);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        L.d(TAG, ">>>>>>>>onConfigurationChanged");
        super.onConfigurationChanged(newConfig);
    }

    @Override
    public void onTerminate() {
        // 程序终止的时候执行
        L.d(TAG, ">>>>>>>>onTerminate");
        super.onTerminate();
    }

    private void initBugfy() {
        Context context = getApplicationContext();
        // 获取当前包名
        String packageName = context.getPackageName();
        // 获取当前进程名
        String processName = getProcessName(android.os.Process.myPid());
        // 设置是否为上报进程
        CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(context);
        strategy.setUploadProcess(processName == null || processName.equals(packageName));
        // 初始化Bugly
        CrashReport.initCrashReport(context, "63f0513123", false, strategy);
        String phone = SPUtils.getPhone();
        if (!TextUtils.isEmpty(phone)) {
            CrashReport.setUserId(phone);
        }
        // 如果通过“AndroidManifest.xml”来配置APP信息，初始化方法如下
        // CrashReport.initCrashReport(context, strategy);
    }

    /**
     * 获取进程号对应的进程名
     *
     * @param pid 进程号
     * @return 进程名
     */
    private static String getProcessName(int pid) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline"));
            String processName = reader.readLine();
            if (!TextUtils.isEmpty(processName)) {
                processName = processName.trim();
            }
            return processName;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }
        return null;
    }


    /**
     * 添加Activity到堆栈
     */
    public void addActivity(Activity activity) {
        if (activityStack == null) {
            activityStack = new Stack<Activity>();
        }
        activityStack.add(activity);
    }

    /**
     * 结束所有Activity
     */
    public void finishAllActivity() {
        for (int i = 0, size = activityStack.size(); i < size; i++) {
            if (null != activityStack.get(i)) {
                activityStack.get(i).finish();
            }
        }
        activityStack.clear();
    }

}
